package com.boot.netty.demo1;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.util.Date;
import java.util.Scanner;

public class SimpleNettyClient {

    private static final String HOST = "127.0.0.1"; // 服务器地址
    private static final int PORT = 8080; // 服务器端口

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = configureBootstrap(workerGroup);
            ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync();
            handleUserInput(channelFuture);
            channelFuture.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    private static Bootstrap configureBootstrap(EventLoopGroup workerGroup) {
        return new Bootstrap()
                .group(workerGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                        ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
                        ch.pipeline().addLast(new SimpleClientHandler());
                    }
                });
    }

    private static void handleUserInput(ChannelFuture channelFuture) {
        System.out.println("请输入消息（输入'exit'退出程序）:");
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String userInput = scanner.nextLine();
            if ("exit".equalsIgnoreCase(userInput)) {
                break;
            }
            channelFuture.channel().writeAndFlush(userInput);
        }
    }

    static class SimpleClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            System.out.println(new Date() + ":客户端写出数据");

            //获取数据
            ByteBuf buffer = getByteBuf(ctx);
            //写数据
            ctx.channel().writeAndFlush(buffer);
        }

        private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
            //获取二进制抽象ByteBuf
            ByteBuf buffer = ctx.alloc().buffer();

            //准备数据，指定好字符串的字符集为UTF-8
            byte[] bytes = "Hello, world!".getBytes(Charset.forName("utf-8"));

            //填充数据到ByteBuf
            buffer.writeBytes(bytes);

            return buffer;
        }
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            ByteBuf byteBuf = (ByteBuf) msg;

            System.out.println(new Date() + ": 客户端读到数据 -> " + byteBuf.toString(Charset.forName("utf-8")));
        }
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    }
}